const express = require("express");
const axios = require("axios");
const router = express.Router();
const { WX_PAY_URL, randomString } = require("../utils/index");
const MD5 = require("js-md5");
const fs = require("fs");
const xmlparser = require("express-xml-bodyparser");
const Order = require("../mongoose/models/order");

/**
 * 用户列表
 */
router.post("/getWxParams", async function (req, res, next) {
  const { out_trade_no, openid, total_fee } = req.body;
  console.log(req.body, "req.body");

  let appid = "wxa295b5ba89f40221"; //应用 APPID
  let mch_id = "1614252433"; //微信支付商户号
  let key = "whjxcapiv3myglackismedoyounoiget"; //微信商户 API 密钥
  let nonce_str = randomString(32, 1); //随机字符串 32算法
  let fee_type = "CNY"; //标价币种
  let body = "为美食买单~"; //内容
  let spbill_create_ip = "183.158.237.74"; //获得用户设备 IP 159.75.2.100
  let notify_url = "https://mail.glack.net/wmjapi/wxpay/notify_url"; //回调地址
  let trade_type = "JSAPI"; //交易类型 具体看 API 里面有详细介绍
  let signA = `appid=${appid}&attach=${out_trade_no}&body=${body}&fee_type=${fee_type}&mch_id=${mch_id}&nonce_str=${nonce_str}&notify_url=${notify_url}&openid=${openid}&out_trade_no=${out_trade_no}&spbill_create_ip=${spbill_create_ip}&total_fee=${total_fee}&trade_type=${trade_type}`;
  console.log(signA, "signA");
  let strSignTmp = signA + `&key=${key}`; //拼接字符串  注意顺序微信有个测试网址 顺序按照他的来 直接点下面的校正测试 包括下面 XML  是否正确
  console.log(strSignTmp, "strSignTmp");
  let sign = MD5(strSignTmp).toUpperCase(); // MD5 后转换成大写
  console.log(sign, "sign");
  let post_data = `<xml>
    <appid>${appid}</appid>
    <mch_id>${mch_id}</mch_id>
    <body>${body}</body>
    <openid>${openid}</openid>
    <fee_type>${fee_type}</fee_type>
    <out_trade_no>${out_trade_no}</out_trade_no>
    <total_fee>${total_fee}</total_fee>
    <spbill_create_ip>${spbill_create_ip}</spbill_create_ip>
    <notify_url>${notify_url}</notify_url>
    <trade_type>${trade_type}</trade_type>
    <attach>${out_trade_no}</attach>
    <nonce_str>${nonce_str}</nonce_str>
    <sign>${sign}</sign>
  </xml>`; //拼接成 XML 格式
  console.log(post_data, "post_datatest");
  console.log(sign, "signtest");
  let url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; //微信传参地址
  try {
    const result = await axios({
      method: "post",
      url: url,
      data: post_data,
      headers: {
        "Content-Type": "application/xml",
      },
    });
    console.log(result.data, "result");
    if (
      result.data
        .split("<return_code><![CDATA[")[1]
        .split("]]></return_code>")[0] == "SUCCESS"
    ) {
      let playeid = result.data
        .split("<prepay_id><![CDATA[")[1]
        .split("]]></prepay_id>")[0];
      console.log(playeid);

      let TimeStamp = `${String(new Date().getTime() / 1000).split(".")[0]}`;
      let NonceStr = MD5(TimeStamp + Math.round(Math.random() * 1000));
      let Package = "prepay_id=" + playeid;
      let SignType = "MD5";
      // 以上部分是参数，以下生成签名
      let Sign = MD5(
        `appId=${appid}&nonceStr=${NonceStr}&package=${Package}&signType=${SignType}&timeStamp=${TimeStamp}&key=${key}`
      );
      // 获取数组，返回到小程序
      let data = {
        timeStamp: TimeStamp,
        nonceStr: NonceStr,
        package: Package,
        signType: SignType,
        paySign: Sign,
      };
      console.log(data, "data");

      res.send({
        code: 1,
        data,
      });
    }

    // console.log(result, "result");
  } catch (error) {
    console.log(error);

    res.send({
      code: 500,
      data: "请求出错",
    });
  }
});

router.post(
  "/notify_url",
  xmlparser({ trim: false, explicitArray: false }),
  function (req, res, next) {
    try {
      const { out_trade_no, return_code, result_code } = req.body.xml;
      
      fs.writeFileSync(__dirname + "/./txt/notify_url.txt", JSON.stringify(req.body.xml));

      if(return_code === 'SUCCESS' && result_code === 'SUCCESS'){
        Order.findOneAndUpdate({ order_no: out_trade_no }, { status: '1', easy_no: getEasyNo(), order_status: '制作中', payObj: req.body.xml }, null, (err, data) => {
          if (err) {
            console.log(err, 'err 没有找到订单~');
            res.send({
              code: 500,
              data: "网络错误 " + err,
            });
            return;
          }
          res.send({
            code: 1,
            data: "修改成功",
          });
        });
      }else{
        Order.findOneAndUpdate({ order_no: out_trade_no }, { status: '3', easy_no: getEasyNo(), order_status: '支付失败', payObj: req.body.xml }, null, (err, data) => {
          if (err) {
            console.log(err, 'err 没有找到订单~');
            res.send({
              code: 500,
              data: "网络错误 " + err,
            });
            return;
          }
          res.send({
            code: 500,
            data: "订单未成功支付",
          });
        });
      }
      
    } catch (error) {
      res.send({
        code: 500,
        data: error,
      });
    }
  }
);


function getEasyNo(){
  const text = fs.readFileSync(__dirname + "/./txt/easy_no.txt", 'utf-8')
  console.log(text, 'text');
  fs.writeFileSync(__dirname + "/./txt/easy_no.txt", String(Number(text) + 1));
  return text
}

module.exports = router;
